import os
import cv2

def extract_frames(video_path, output_folder, interval=1):
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print(f"无法打开视频文件: {video_path}")
        return

    base_name = os.path.splitext(os.path.basename(video_path))[0]

    frame_count = 0
    saved_count = 0

    while True:
        ret, frame = cap.read()
        if not ret:
            break

        if frame_count % interval == 0:
            filename = os.path.join(output_folder, f"{base_name}_frame_{frame_count:06d}.jpg")
            cv2.imwrite(filename, frame)
            saved_count += 1

        frame_count += 1

    cap.release()
    print(f"视频【{base_name}】总共保存了 {saved_count} 张图片到 {output_folder}")

if __name__ == "__main__":
    video_path = "/Users/shrek/Documents/proj/bilibili_data/001.mp4"  # 替换成你的视频文件路径
    output_folder = "/Users/shrek/Documents/proj/bilibili_data/images_001"  # 图片输出目录
    interval = 6  # 每帧保存一张，可以修改成 5、10 等

    extract_frames(video_path, output_folder, interval)
